import os
import sys
import re
import urllib2

class Direction:
    def __init__(self, routeSymbol):
        self.url = 'http://www.nextmuni.com/predictor/stopSelectorDataFrame.jsp?a=sf-muni&r=%s' % routeSymbol
        
#parent.addOption(directionSelector, "Inbound to Church & Market", "F__IBMRKT", false, true);
        self.directionRegex = re.compile('.*?parent\.addOption\(directionSelector,\s+"(.*?)",\s+"(.*?)",(.*)', 
                                           re.DOTALL)

        self.nameArr = []
        self.symbolArr = []

        self.loadDirections()

    def parseDirection(self, htmlStr):
        m = self.directionRegex.match(htmlStr)

        if (m == None):
            return (None, None, None)

        return (m.group(1), m.group(2), m.group(3))

    def loadDirections(self):
        req = urllib2.Request(self.url)
        response = urllib2.urlopen(req)
        htmlStr = response.read()

        # print "htmlStr: %s" % htmlStr

        self.nameArr = []
        self.symbolArr = []
        
        (name, symbol, restOfHtmlStr) = self.parseDirection(htmlStr)
        while (restOfHtmlStr != None):
            self.nameArr.append(name)
            self.symbolArr.append(symbol)
          
            # print "%s: %s" % (name, symbol)
  
            (name, symbol, restOfHtmlStr) = self.parseDirection(restOfHtmlStr) 

    def getName(self, symbol):
        for i in range(0, len(self.symbolArr)):
            currSymbol = self.symbolArr[i]
            if (currSymbol == symbol):
                return self.nameArr[i]

        return None

    def getSymbol(self, name):
        for i in range(0, len(self.nameArr)):
            currName = self.nameArr[i]
            if (currName == name):
                return self.symbolArr[i]

        return None


            
